/**
 * 
 */
package com.demo2do.boyle.backend.service.impl;

import java.util.List;

import org.apache.commons.lang3.ClassUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.demo2do.boyle.backend.service.DataService;
import com.demo2do.core.persistence.GenericDaoSupport;
import com.demo2do.core.persistence.support.Filter;
import com.demo2do.core.service.impl.GenericServiceImpl;
import com.demo2do.core.web.resolver.Page;

/**
 * @author Wilson
 *
 */
@Service("dataService")
public class DataServiceImpl<T> extends GenericServiceImpl<T> implements DataService<T> {
    
    @Autowired
    private GenericDaoSupport genericDaoSupport;

    /* (non-Javadoc)
     * @see com.demo2do.boyle.backend.service.DataService#count(java.lang.Class)
     */
    public int count(Class<T> clazz) {
    	return genericDaoSupport.searchForInt("SELECT COUNT(1) FROM " + ClassUtils.getShortClassName(clazz) + " WHERE disabled = false");
    }

    /* (non-Javadoc)
     * @see com.demo2do.boyle.backend.service.DataService#count(java.lang.Class, com.demo2do.core.persistence.support.Filter)
     */
    public int count(Class<T> clazz, Filter filter) {
    	return genericDaoSupport.searchForInt("SELECT COUNT(1) FROM " + ClassUtils.getShortClassName(clazz) + filter.getWhereSentence(), filter.getParameters());
    }
    
    /* (non-Javadoc)
     * @see com.demo2do.boyle.backend.service.DataService#listAll(java.lang.Class)
     */
    @SuppressWarnings("unchecked")
	public List<T> listAll(Class<T> clazz) {
    	return genericDaoSupport.searchForList("FROM " + ClassUtils.getShortClassName(clazz) + " WHERE disabled = false");
    }

    /* (non-Javadoc)
     * @see com.demo2do.boyle.backend.service.DataService#listByPage(java.lang.Class, com.demo2do.core.web.resolver.Page)
     */
    @SuppressWarnings("unchecked")
	public List<T> listByPage(Class<T> clazz, Page page) {
    	List<T> result = genericDaoSupport.searchForList("FROM " + ClassUtils.getShortClassName(clazz) + " WHERE disabled = false", page.getBeginIndex(), page.getMaxResultRecords());
        page.calculate(result.size());
        return result.size() > page.getEveryPage() ? result.subList(0, page.getEveryPage()) : result;
    }

}
